package com.personal.site.utils;

import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.captcha.ShearCaptcha;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

public class CaptchaUtil {

    private static Integer width = 102;

    private static Integer height = 40;

    private static Integer length = 6;
    public static String createCaptcha(String captchaString){
        ShearCaptcha shearCaptcha = cn.hutool.captcha.CaptchaUtil.createShearCaptcha(width, height, length, 2);
        BufferedImage image = (BufferedImage)shearCaptcha.createImage(captchaString);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try{
            ImageIO.write(image,"png",bos);
        }catch (IOException e){
            e.printStackTrace();
        }
        Base64.Encoder encoder = Base64.getEncoder();
        byte[] encode = encoder.encode(bos.toByteArray());
        String s = new String(encode);
        s = s.replaceAll("\n","").replaceAll("\r","");
        return "data:image/png;base64,"+s;
    }
}
